//
//  ResetViewController.m
//  FDSMeshLibDemo
//
//  Created by linkiing on 2024/6/24.
//

#import "ResetViewController.h"
#import "SearchDeviceTableViewCell.h"

@interface ResetViewController ()

@property (nonatomic, strong) MeshTool *meshTool;
@property (nonatomic, strong) NSMutableArray *peripheralList;
@property (nonatomic, strong) NSMutableArray *selectDeviceList;

@property (weak, nonatomic) IBOutlet UILabel *scanLabel;
@property (weak, nonatomic) IBOutlet UIButton *configButton;
@property (weak, nonatomic) IBOutlet UITableView *tableview;

@end

@implementation ResetViewController

#pragma mark - Initialize
- (void)InitializeCode{
    self.title = @"重置设备";
    self.meshTool = [MeshTool shareInstance];
    self.peripheralList = [NSMutableArray array];
    self.selectDeviceList = [NSMutableArray array];
    self.configButton.layer.cornerRadius = 22;
    self.configButton.layer.masksToBounds = YES;
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"setting_09"] style:(UIBarButtonItemStylePlain) target:self action:@selector(clickRefreshItem)];
    self.navigationItem.rightBarButtonItem = rightItem;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self InitializeCode];
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self startScanMeshDevice];
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [FDSMeshApi stopScan];
}
#pragma mark - UIButton
- (void)clickRefreshItem{
    self.scanLabel.text = @"可重置设备";
    [self.selectDeviceList removeAllObjects];
    [self.peripheralList removeAllObjects];
    [self.tableview reloadData];
    [self startScanMeshDevice];
}
- (void)startScanMeshDevice{
    [FDSMeshApi startScanProvisionedDevice:@"GD_LED" completion:^(CBPeripheral * _Nonnull peripheral) {
        if (([peripheral.device_firmwareVersion compare:@"000055"] != NSOrderedAscending)) {
            if (![self.peripheralList containsObject:peripheral]) {
                [self.peripheralList addObject:peripheral];
                self.scanLabel.text = [NSString stringWithFormat:@"可重置设备：%lu",(unsigned long)self.peripheralList.count];
                [self.tableview reloadData];
            }
        }
    }];
}
- (IBAction)clickResetMeshBtn:(UIButton *)sender{
    if (self.selectDeviceList.count == 0) {
        [SVProgressHUD showErrorWithStatus:@"未选中设备！"];
    } else {
        NSMutableArray *macAddressList = [NSMutableArray array];
        for (NSInteger i=0; i<self.selectDeviceList.count;i++) {
            CBPeripheral *peripheral = self.selectDeviceList[i];
            [macAddressList addObject:peripheral.device_macAddress];
        }
        __block NSInteger progressIndex = 0;
        [SVProgressHUD showProgress:0 status:[NSString stringWithFormat:@"重置进度：%ld/%lu",(long)progressIndex, (unsigned long)self.selectDeviceList.count]];
        [FDSMeshApi batchAdvertRemoveNode:macAddressList progressAction:^(NSString * _Nonnull macAddress) {
            progressIndex++;
            CGFloat progressPercent = (CGFloat)progressIndex/self.selectDeviceList.count;
            [SVProgressHUD showProgress:progressPercent status:[NSString stringWithFormat:@"重置进度：%ld/%lu",(long)progressIndex, (unsigned long)self.selectDeviceList.count]];
        } resultAction:^(BOOL finish) {
            dispatch_async(dispatch_get_main_queue(), ^{
                if (finish) {
                    [SVProgressHUD showSuccessWithStatus:@"重置成功"];
                } else {
                    [SVProgressHUD showErrorWithStatus:@"重置失败！"];
                }
                [self clickRefreshItem];
            });
        }];
    }
}
- (IBAction)clickSelectAllBtn:(UIButton *)sender {
    sender.selected = !sender.selected;
    if (sender.selected) {
        [self.selectDeviceList setArray:self.peripheralList];
    } else {
        [self.selectDeviceList removeAllObjects];
    }
    NSLog(@"选择的设备数：%lu",(unsigned long)self.selectDeviceList.count);
    [self.tableview reloadData];
}
#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.peripheralList.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 100;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.01;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.01;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    SearchDeviceTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([SearchDeviceTableViewCell class])];
    if (!cell){
        cell = [[NSBundle mainBundle] loadNibNamed:@"SearchDeviceTableViewCell" owner:nil options:nil][0];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    CBPeripheral *peripheral = self.peripheralList[indexPath.row];
    cell.titleLabel.text = peripheral.device_name;
    cell.subTitleLabel.text = [NSString stringWithFormat:@"%@ - %@, RSSI: %@, Version: %@", peripheral.device_type, peripheral.device_macAddress, peripheral.device_rssi, peripheral.device_firmwareVersion];
    cell.iconImageview.image = [UIImage imageNamed:@"setting_05"];
    if ([self.selectDeviceList containsObject:peripheral]) {
        cell.selectImageview.image = [UIImage imageNamed:@"setting_02"];
    } else {
        cell.selectImageview.image = [UIImage imageNamed:@"setting_01"];
    }
    return cell;
}
#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    CBPeripheral *peripheral = self.peripheralList[indexPath.row];
    if ([self.selectDeviceList containsObject:peripheral]) {
        [self.selectDeviceList removeObject:peripheral];
    } else {
        [self.selectDeviceList addObject:peripheral];
    }
    [self.tableview reloadData];
}

@end
